package com.jrx.anytxn.transaction.job.fileRepay.config;

import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlFilePaymentLog;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.bean.FilePaymentSaveBean;
import com.jrx.anytxn.transaction.config.AnytxnBatchProperties;
import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlThirdPartyPayment;
import com.jrx.anytxn.transaction.job.fileRepay.step.*;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理正常文件还款
 * @author  jing.xy
 */
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class DealPayFileConfiguration {

    Logger logger = LoggerFactory.getLogger(DealPayFileConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Resource(name = "paramSqlSessionFactory")
    SqlSessionFactory paramSqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;
    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private FilePayProcessor filePayProcessor;
    @Autowired
    private FilePreProcessor filePreProcessor;
    @Autowired
    private FilePayWriter filePayWriter;
    @Autowired
    private FilePreWriter filePreWriter;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private DealPayListener dealPayListener;
    @Autowired
    private PaphFileConfig paphFileConfig;


    @Bean
    public Job dealPayFileJob() {
        return jobBuilderFactory.get("dealPayFileJob")
                .start(checkDealPayFileStep())
                .next(payPreStep())
                .next(payStep())
                .build();
    }

    @Bean
    public Step checkDealPayFileStep() {
        return stepBuilderFactory.get("checkDealPayFileStep")
                .tasklet(checkPayTasklet())
                .build();
    }

    private Tasklet checkPayTasklet() {
        return (stepContribution, chunkContext) -> {
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            int dealCount = extBtBatchStatusMapper.selectByBusiDateAndJobName(org.getNextProcessingDate(),TransBizConstant.DEAL_PAY_FILE_JOB+paphFileConfig.getFileType(),org.getTenantId());
            if(dealCount > 0){
                logger.info("已处理过文件");
                throw new RuntimeException("已处理");
            }
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Step payPreStep() {
        return stepBuilderFactory.get("payPreStep")
                .<TlFilePaymentLog, TlThirdPartyPayment>chunk(anytxnBatchProperties.getFileRepayConfig().getChunkLimit())//表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(payPreReader())
                .processor(filePreProcessor)
                .writer(filePreWriter)
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getFileRepayConfig().getThrottleLimit())//多线程
                .build();
    }

    @Bean
    public Step payStep() {
        return stepBuilderFactory.get("payStep")
                .listener(dealPayListener)
                .<TlThirdPartyPayment, FilePaymentSaveBean>chunk(anytxnBatchProperties.getFileRepayConfig().getChunkLimit())//表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(payReader())
                .processor(filePayProcessor)
                .writer(filePayWriter)
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getFileRepayConfig().getThrottleLimit())//多线程
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<TlFilePaymentLog> payPreReader() {
        MyBatisCursorItemReader<TlFilePaymentLog> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(paramSqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.param.mapper.ext.ExtTlFilePaymentLogMapper.selectPaymentLogForBatch");
        Map<String, Object> map = new HashMap<>();

        PrOrganizationTable organizationTable = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        map.put("tradeDate",organizationTable.getNextProcessingDate());
        map.put("tradeFlagList", Arrays.asList(TransBizConstant.FILE_TRADE_FLAG_0,TransBizConstant.FILE_TRADE_FLAG_2));

        cursorItemReader.setParameterValues(map);
        SynchronizedItemStreamReader<TlFilePaymentLog> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<TlThirdPartyPayment> payReader() {
        MyBatisCursorItemReader<TlThirdPartyPayment> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.transaction.mapper.ext.ExtTlThirdPartyPaymentMapper.selectFilePayForBatch");
        Map<String, Object> map = new HashMap<>();

        PrOrganizationTable organizationTable = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        map.put("businessDate",organizationTable.getNextProcessingDate());
        map.put("paymentTypeList", Arrays.asList(TransBizConstant.REPAYMENT_TYPE_PAY,TransBizConstant.REPAYMENT_TYPE_OVERDUE));
        map.put("channel",TransBizConstant.PAPH_CHANNEL);
        map.put("sumStatus",TransBizConstant.THIRD_PARTY_STATUS_W);

        cursorItemReader.setParameterValues(map);
        SynchronizedItemStreamReader<TlThirdPartyPayment> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }


}
